//
//  RukouViewController.m
//  SnapCAD
//
//  Created by Developer on 2025/1/27.
//

#import "RukouViewController.h"
#import "Masonry.h"

@interface RukouViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation RukouViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupConstraints];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 恢复导航栏
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 设置头部视图
    [self setupHeader];
    
    // 设置滚动视图
    [self setupScrollView];
}

- (void)setupHeader {
    // 头部视图
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];
    
    // 返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = [UIColor colorWithRed:0.40 green:0.49 blue:0.93 alpha:1.0];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.backButton];
    
    // 标题标签
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Open DWG files from Other Applications";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textColor = [UIColor blackColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.titleLabel];
}

- (void)setupScrollView {
    // 滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.showsHorizontalScrollIndicator = YES;
    self.scrollView.minimumZoomScale = 0.5;
    self.scrollView.maximumZoomScale = 3.0;
    self.scrollView.delegate = self;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];
    
    // 图片视图
    self.imageView = [[UIImageView alloc] init];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.clipsToBounds = YES;
    self.imageView.userInteractionEnabled = YES;
    
    // 设置一张示例图片，你可以替换为你需要的图片
    UIImage *placeholderImage = [UIImage imageNamed:@"tipsInfo"];
    if (placeholderImage) {
        self.imageView.image = placeholderImage;
    } else {
        // 如果没有图片，创建一个占位图
        self.imageView.backgroundColor = [UIColor lightGrayColor];
        UILabel *placeholderLabel = [[UILabel alloc] init];
        placeholderLabel.text = @"Image will be displayed here";
        placeholderLabel.textAlignment = NSTextAlignmentCenter;
        placeholderLabel.textColor = [UIColor darkGrayColor];
        placeholderLabel.font = [UIFont systemFontOfSize:16];
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.imageView addSubview:placeholderLabel];
        
        [placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.imageView);
        }];
    }
    
    self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.imageView];
    
    // 添加双击手势来重置缩放
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    [self.scrollView addGestureRecognizer:doubleTap];
}

- (void)setupConstraints {
    // 返回按钮约束
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(10);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    // 标题标签约束
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.backButton);
        make.left.greaterThanOrEqualTo(self.backButton.mas_right).offset(8);
        make.right.lessThanOrEqualTo(self.view).offset(-60);
    }];
    
    // 头部视图约束
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.backButton.mas_bottom).offset(10);
    }];
    
    // 滚动视图约束
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    // 图片视图约束
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
        make.height.equalTo(self.scrollView).priorityHigh();
    }];
}

- (void)loadImageFromURL:(NSString *)imageURL {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:imageURL];
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:imageData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (image) {
                self.imageView.image = image;
                [self updateImageViewConstraints];
            }
        });
    });
}

- (void)updateImageViewConstraints {
    UIImage *image = self.imageView.image;
    if (image) {
        CGFloat aspectRatio = image.size.height / image.size.width;
        
        [self.imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.scrollView);
            make.width.equalTo(self.scrollView);
            make.height.equalTo(self.scrollView.mas_width).multipliedBy(aspectRatio);
            make.bottom.equalTo(self.scrollView).priorityHigh();
        }];
        
        // 更新滚动视图的内容大小
        [self.view layoutIfNeeded];
        self.scrollView.contentSize = self.imageView.frame.size;
    }
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    // 保持图片在中心位置
    CGFloat offsetX = MAX((scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5, 0.0);
    CGFloat offsetY = MAX((scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5, 0.0);
    
    self.imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                       scrollView.contentSize.height * 0.5 + offsetY);
}

#pragma mark - Gesture Actions

- (void)handleDoubleTap:(UITapGestureRecognizer *)gesture {
    if (self.scrollView.zoomScale > self.scrollView.minimumZoomScale) {
        [self.scrollView setZoomScale:self.scrollView.minimumZoomScale animated:YES];
    } else {
        CGPoint touchPoint = [gesture locationInView:self.imageView];
        CGFloat zoomScale = self.scrollView.maximumZoomScale;
        CGFloat width = self.scrollView.frame.size.width / zoomScale;
        CGFloat height = self.scrollView.frame.size.height / zoomScale;
        CGRect zoomRect = CGRectMake(touchPoint.x - width/2, touchPoint.y - height/2, width, height);
        [self.scrollView zoomToRect:zoomRect animated:YES];
    }
}

#pragma mark - Button Actions

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
